import {
	TOKEN,
	BACK_URL
} from '../config/cachekey.js'
import Cache from '@/utils/cache.js'
import base from '../config/app.js'
import {
	useUserStore
} from '@/stores/user.js'
var store = null;
const {
	baseURL
} = base;

import Request from 'luch-request' //npm下载引入luch-request

const http = new Request({
	baseURL: baseURL, //设置请求的base url
	timeout: 300000, //超时时长5分钟,
})

//请求拦截器
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
	const token = Cache.get(TOKEN);
	if (token) {
		config.header['Authorization'] = token;
	}
	// if (config.method === 'POST') {
	// 	config.data = JSON.stringify(config.data);
	// }
	return config
}, error => {
	return Promise.resolve(error)
})

// 响应拦截器
http.interceptors.response.use((response) => {
	if(!store) {
		store = useUserStore()
	}
	if (response.data.code != 200) {
		uni.showToast({
			title: response.data.msg,
			icon: 'none'
		})
	}
	if (response.data.code == 401) {
		store.logOut();
		uni.redirectTo({
			url: '/pages/login/login'
		})
	}
	return response.data
}, (error) => {
	//未登录时清空缓存跳转
	if (error.statusCode == 401) {
		store.logOut();
		uni.redirectTo({
			url: '/pages/login/login'
		})
	}
	return Promise.resolve(error)
})
export default http;